/**
 * Copyright(c) kyle.
 */
package org.example.metrics;

import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;

import java.util.concurrent.TimeUnit;

import static java.util.concurrent.ThreadLocalRandom.current;

/**
 * Meter主要用来测量一组事件发生的速率，
 * 比如，我们可以用它来度量某个服务接口被调用的频率，
 * 甚至可以用它来度量某些网络操作的吞吐量
 *
 * @author kyle
 * @version 1.00.00
 * @updateUser [Kyle]
 * @updateRemark [说明本次修改内容]
 * @date [2021-09-21 12:51]
 * @since [2021-09-21 12:51]
 */
public class MeterExample {
    public static final MetricRegistry registry = new MetricRegistry();
    public static final Meter sizeMeter = registry.meter("volume");
    private static final Meter requestMeter = registry.meter("tqs");

    public static void main(String[] args) {
        //定义运行的相关参数
        ConsoleReporter reporter = ConsoleReporter.forRegistry(registry)
                .convertRatesTo(TimeUnit.MINUTES)
                .convertDurationsTo(TimeUnit.MINUTES)
                .build();
        //每隔十秒运行一次
        reporter.start(10, TimeUnit.SECONDS);
        while (true) {
            upload(new byte[current().nextInt(1000)]);
            randomSleep();
        }
    }

    private static void randomSleep() {
        try {
            TimeUnit.SECONDS.sleep(current().nextInt(10));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void upload(byte[] request) {
        //记录调用次数
        requestMeter.mark();
        //记录数据包大小
        sizeMeter.mark(request.length);
    }
}
